package com.sx.pay.service.wepay;

import com.sx.utils.HttpService;
import com.sx.utils.PasswordUtils;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;

/**
 * @author AdinZ
 * @date 2020/11/7 15:28
 */
public class TenpayUtil {


    /**
     * 微信退款请求地址
     */
    public static final String WX_REFUND_URL = "https://api.mch.weixin.qq.com/secapi/pay/refund";

    public static String getRequestXml(SortedMap<Object,Object> parameters, String sign){
        StringBuffer sb = new StringBuffer();
        sb.append("<xml>");
        Set es = parameters.entrySet();
        Iterator it = es.iterator();
        while(it.hasNext()) {
            Map.Entry entry = (Map.Entry)it.next();
            String k = (String)entry.getKey();
            String v = (String)entry.getValue();
            if ("attach".equalsIgnoreCase(k)||"body".equalsIgnoreCase(k)||"sign".equalsIgnoreCase(k)) {
                sb.append("<"+k+">"+"<![CDATA["+v+"]]></"+k+">");
            }else {
                sb.append("<"+k+">"+"<![CDATA["+v+"]]></"+k+">");
            }
        }
        sb.append("<sign>"+"<![CDATA["+sign+"]]></sign>");
        sb.append("</xml>");
        return sb.toString();
    }

    public static String createSign(SortedMap<Object,Object> parameters,String key){
        StringBuffer sb = new StringBuffer();
        Set es = parameters.entrySet();
        Iterator it = es.iterator();
        while(it.hasNext()) {
            Map.Entry entry = (Map.Entry)it.next();
            String k = (String)entry.getKey();
            Object v = entry.getValue();
            if(null != v && !"".equals(v)
                    && !"sign".equals(k) && !"key".equals(k)) {
                sb.append(k + "=" + v + "&");
            }
        }
        sb.append("key=" +key);
        String sign = PasswordUtils.getInstance().md5(sb.toString()).toUpperCase();
        return sign;
    }


    public static String Unifiedorder(String requestXML) throws IOException {
        String requestUrl="https://api.mch.weixin.qq.com/pay/unifiedorder";
        String result = HttpService.getInstance().post(requestUrl, requestXML,"application/xml");
        return result;
    }

}
